package com.atguigu.yygh.sms.controller.front;


import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.sms.service.SmsService;
import com.atguigu.yygh.sms.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags = "短信接口")
@RestController
@RequestMapping("/front/sms")
public class FrontSmsController {
    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation("发送短信")
    @PostMapping("/send/{phone}")
    public R code(@PathVariable String phone) {
        //在有效期内，验证码可以不需要重复发送
        String code = redisTemplate.opsForValue().get("code:" + phone);
        if(!StringUtils.isEmpty(code)) return R.error().message("上一次发送的验证码5分钟内有效");

        //生成四位随机数验证码
        code = RandomUtil.getFourBitRandom();

        //发送短信
           smsService.send(phone,code);

        //存储验证码到Redis中,存储5分钟
        redisTemplate.opsForValue().set("code:"+phone, code, 5, TimeUnit.MINUTES);

        return R.ok().message("验证码发送成功");
    }
}
